﻿using Microsoft.CSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using CATALooK;
using System.Reflection;
using System.Linq;


namespace Aricie.DNN.Services.Url.FriendlyUrl.Providers
{

    public class CatalookUrlRewriter : IUrlRewriterProvider, IIsActive
    {


        private Assembly CATAssembly { get; set; }

        public CatalookUrlRewriter()
        {
            CATAssembly = Assembly.Load("CATALooKStore");
        }

        List<GroupParamsRewrite> IFriendlyUrlGroupProvider.GetRewrites()
        {
            List<GroupParamsRewrite> toReturn = new List<GroupParamsRewrite>();
            string desc = "Name of the catalook product being browsed";
            toReturn.Add(new GroupParamsRewrite("ProductName", desc, RewriteType.SubPath, UrlParam.FromSyntax("ProductID")) { Localized = true });
            desc = "Name of the catalook category being browsed";
            toReturn.Add(new GroupParamsRewrite("CategoryName", desc, RewriteType.SubPath, UrlParam.FromSyntax("CategoryID")) { Localized = true });
            desc = "Name of the catalook advanced category being browsed";
            toReturn.Add(new GroupParamsRewrite("AdvCatName", desc, RewriteType.SubPath, UrlParam.FromSyntax("CategoryID")) { Localized = true });
            return toReturn;
        }

        GroupRewriteResult IUrlRewriterProvider.RewriteParams(string groupName, RewriteType objRewriteType, Dictionary<UrlParam, string> parameters, FriendlierUrlStrategy behaviour)
        {
            GroupRewriteResult toReturn = new GroupRewriteResult();

            string culture = System.Threading.Thread.CurrentThread.CurrentCulture.ToString();
            if ((parameters.ContainsKey(UrlParam.Language) && !string.IsNullOrEmpty(parameters[UrlParam.Language])))
            {
                culture = parameters[UrlParam.Language];
            }

            if (parameters.Count > 0)
            {
                int categoryId = -1;
                switch (groupName.ToLowerInvariant())
                {
                    case "productname":
                        int productId = int.Parse(parameters[UrlParam.FromSyntax("productid")], CultureInfo.InvariantCulture);
                        toReturn.RewriteValue = this.GetProductName(productId, culture, behaviour);
                        toReturn.ConsumedParameters[UrlParam.FromSyntax("productid")] = true;
                        break;
                    case "categoryname":
                        categoryId = int.Parse(parameters[UrlParam.FromSyntax("categoryid")], CultureInfo.InvariantCulture);
                        toReturn.RewriteValue = this.GetCategoryName(categoryId, culture, behaviour);
                        toReturn.ConsumedParameters[UrlParam.FromSyntax("categoryid")] = true;
                        break;
                    case "advcatname":
                        categoryId = int.Parse(parameters[UrlParam.FromSyntax("categoryid")], CultureInfo.InvariantCulture);
                        toReturn.RewriteValue = this.GetAdvCategoryName(categoryId, culture, behaviour);
                        toReturn.ConsumedParameters[UrlParam.FromSyntax("categoryid")] = true;
                        break;
                }
            }
            return toReturn;
        }

        public string GetProductName(int productId, string culture, FriendlierUrlStrategy behaviour)
        {
            ProductsDB controller = new ProductsDB();
            Type ctlrType = controller.GetType();
            MethodInfo getSingleProductsMethod = default(MethodInfo);
            ProductInfo objProductInfo = default(ProductInfo);
            getSingleProductsMethod = ctlrType.GetMethod("CAT_GetSingleProducts", new Type[] {
				typeof(int),
				typeof(bool),
				typeof(RequestType),
				typeof(int)
			});
            objProductInfo = (ProductInfo)getSingleProductsMethod.Invoke(controller, new object[] {
				productId,
				false,
				RequestType.AdminRequest,
				NukeHelper.PortalId
			});
            string toReturn = string.Empty;
            if (objProductInfo != null)
            {
                toReturn = GetLocalizedContent(ItemType.Product, productId, 0, objProductInfo.ProductName, NukeHelper.PortalId, string.Empty, culture);
            }
            return toReturn;
        }

        public string GetCategoryName(int categoryId, string culture, FriendlierUrlStrategy behaviour)
        {
            CategoryController controller = new CategoryController();
            CategoryInfo objCategoryInfo = controller.CAT_GetCategory(categoryId, NukeHelper.PortalId);
            string toReturn = string.Empty;
            if (objCategoryInfo != null)
            {
                toReturn = objCategoryInfo.CategoryName;
            }
            return toReturn;
        }

        public string GetAdvCategoryName(int categoryId, string culture, FriendlierUrlStrategy behaviour)
        {
            AdvCatController controller = new AdvCatController();
            AdvCatInfo objAdvCatInfo = controller.GetAdvCat(categoryId);
            string toReturn = string.Empty;
            if (objAdvCatInfo != null)
            {
                toReturn = GetLocalizedContent(ItemType.AdvCat, categoryId, 0, objAdvCatInfo.AdvCatName, NukeHelper.PortalId, string.Empty, culture);
            }
            return toReturn;
        }


        private static MethodInfo LocalizeContentMethod = null;
        private string GetLocalizedContent(ItemType CurrentItemType, int Id, int DBField, string translation, int portalId, string index, string culture)
        {
            dynamic lcType = typeof(LocalizeContent);
            if ((LocalizeContentMethod == null))
            {
                LocalizeContentMethod = ((MethodInfo[])lcType.GetMethods()).Where(mi => mi.Name == "GetLocalizedContent").First();
            }
            List<object> ParamList = new List<object>();
            ParamList.AddRange(new object[] {
				CurrentItemType,
				Id,
				DBField,
				translation,
				portalId,
				index,
				culture
            });

            return LocalizeContentMethod.Invoke(null, ParamList.ToArray()).ToString();
        }

        public bool IsActive
        {
            get { return DotNetNuke.Framework.Reflection.CreateType("CATALooK.ProductsDB, CATALooKStore", true) != null; }
        }
    }
}